﻿using System.Collections.Concurrent;

namespace NordPixel.WPF.UnitOfWork.LiteDb.Core;

public class UnitWork
{
    private readonly ConcurrentDictionary<string, LiteDBContext> _dbContexts;
    private string _currentDbName;

    public UnitWork( ConcurrentDictionary<string, LiteDBContext> contexts )
    {
        _dbContexts = contexts;
        if (!_dbContexts.Any())
        {
            throw new ArgumentException( $"You have to register at least one LiteDB database" );
        }

        _currentDbName = _dbContexts.Keys.FirstOrDefault()!;
    }

    public void UseDatabase( string dbName )
    {
        _currentDbName = _dbContexts.ContainsKey( dbName ) ? dbName : throw new ArgumentException( $"Can't find a registered database with name: {dbName}" );
    }

    public Repository<T> GetRepository<T>() where T : class, new()
    {
        return new Repository<T>( _dbContexts[_currentDbName] );
    }

    public void BeginTransaction()
    {
        _dbContexts[_currentDbName].Database.BeginTrans();
    }

    public void Commit()
    {
        _dbContexts[_currentDbName].Database.Commit();
    }

    public void Rollback()
    {
        _dbContexts[_currentDbName].Database.Rollback();
    }

    public void DisposeAll()
    {
        foreach (var item in _dbContexts.Values)
        {
            item.Database.Dispose();
        }
        //_dbContexts[_currentDbName].Database.Dispose();
    }
}
